package com.hgm.study.extension

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*

/**
 * @author    HGM
 * @version   1.0
 */
@Composable
fun LazyListState.OnBottomReached(buffer: Int = 1, loadMore: () -> Unit) {

      require(buffer >= 0) { "缓存值必须为正整数" }

      //是否应该加载更多的状态
      val shouldLoadMore = remember {
            //这个状态是由另一个状态计算派生而来的
            derivedStateOf {

                  //获取最后显示的item
                  val lastVisibleItem =
                        layoutInfo.visibleItemsInfo.lastOrNull() ?: return@derivedStateOf true

                  //如果最后显示的item是最后一个的话，说明已经触底，需要加载更多
                  lastVisibleItem.index == layoutInfo.totalItemsCount - 1 - buffer
            }
      }


      LaunchedEffect(shouldLoadMore) {
            snapshotFlow { shouldLoadMore.value }
                  .collect {
                        if (it) {
                              loadMore()
                        }
                  }
      }
}